package cn.com.wblog.dao;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;

import org.apache.log4j.Logger;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.sql.Sql;
import org.nutz.lang.Files;

import cn.com.wblog.pojo.Article;
import cn.com.wblog.pojo.ArticleContent;
import cn.com.wblog.utils.Utils;

public class ArticleDao extends AbstractDao {
	private static String IMAGE_ATTACHMENT_DIR = "images";
	
	public ArticleDao(Dao dao) {
		this.dao = dao;
	}
	
	public Article getArticleById(int id) {
		Article article = this.dao.fetch(Article.class, id);
		this.dao.fetchLinks(article, "type");
		this.dao.fetchLinks(article, "content");
		return article;
	}
	
	public boolean save(int userId, int typeId, String title, String content) {
		Article article = new Article(userId, typeId, title);
		article = this.dao.insert(article);
		if (article != null) {
			Sql sql = this.dao.sqls().create("insertArticleContent");
			sql.vars().set("table", "wb_article_content");
			sql.params().set("Id", article.getId()).set("content", content);
			this.dao.execute(sql);
			return true;
		}
		return false;
	}
	
	public boolean update(Article article) {
		this.dao.updateWith(article, "content");
		return true;
	}
	
	public boolean deleteById(int id) {
		this.dao.delete(ArticleContent.class, id);
		this.dao.delete(Article.class, id);
		return true;
	}
	
	public List<Article> getList(int currentPage, int numPerPage, String keyword) {
		List<Article> list = this.dao.query(Article.class, Cnd.where("title", "LIKE", "%"+(keyword==null?"":keyword)+"%"), dao.createPager(currentPage, numPerPage));
		for (Article article : list) {
			this.dao.fetchLinks(article, "user");
			this.dao.fetchLinks(article, "type");
		}
		return list;
	}
	
	public String saveAttachment(File file, String realPath) {
		String dirPath = realPath + ArticleDao.IMAGE_ATTACHMENT_DIR;
		File dir = new File(dirPath);
		if (!dir.exists()) {
			dir.mkdir();
		}
		String oldFileName = file.getName();
		String extension = oldFileName.substring(oldFileName.lastIndexOf("."));
		String newFileName = Utils.renameFile() + extension;
		File newFile = new File(dir, newFileName);
		try {
			Files.move(file, newFile);
		} catch (IOException ioex) {
			Logger.getLogger(ArticleDao.class.getName());
		}
		return "/wblog/" + ArticleDao.IMAGE_ATTACHMENT_DIR + "/" + newFileName;
	}
}
